package com.ruoyi.web.controller.api;


import com.ruoyi.cat.domain.CatOutsiderealmTable;
import com.ruoyi.cat.domain.DTO.ArticletaskDTO;
import com.ruoyi.cat.service.ICatArticletaskTableService;
import com.ruoyi.cat.service.ICatOutsiderealmTableService;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.Base64Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.net.URLEncoder;
import java.util.Random;

@RestController
public class VerifyFileController {


    @Autowired
    private ICatArticletaskTableService catArticletaskTableService;


    @Autowired
    private ICatOutsiderealmTableService iCatOutsiderealmTableService;

/*
    @GetMapping("/")
    public ResponseEntity<?> handleDomainRequest(HttpServletRequest request) {
        String domain = request.getServerName();
        System.out.println(domain);
       */
/* Long articleId = domainArticleMapping.get(domain);

        if (articleId == null) {
            return ResponseEntity.notFound().build();
        }

        Article article = articleService.getArticleById(articleId);*//*

        return ResponseEntity.ok("");
    }
*/

    @PostMapping("/upload")
    public ResponseEntity<String> uploadFile(@RequestParam("file") MultipartFile file) {
        try {
            String filePath = RuoYiConfig.getUploadPath();

            // 创建文件存储目录
            File uploadDir = new File(filePath);
            if (!uploadDir.exists()) {
                uploadDir.mkdirs();
            }

            // 获取文件名
            String fileName = file.getOriginalFilename();

            // 创建目标文件对象
            File dest = new File(uploadDir.getAbsolutePath() + File.separator + fileName);

            // 如果文件已存在，先删除它
            if (dest.exists()) {
                dest.delete();
            }

            // 保存新文件
            file.transferTo(dest);

            return ResponseEntity.ok("文件上传成功");
        } catch (IOException e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body("文件上传失败: " + e.getMessage());
        }
    }

    // 文件访问接口
    @GetMapping("/{fileName:.+}")
    public ResponseEntity<String> getVerifyFile(@PathVariable String fileName) {
        try {
            System.out.println("=====文件访问接口======"+fileName);
            String filePath = RuoYiConfig.getUploadPath();
            File file = new File(filePath + File.separator + fileName);
            if (!file.exists()) {
                return ResponseEntity.notFound().build();
            }

            // 使用 BufferedReader 读取文件内容
            StringBuilder content = new StringBuilder();
            try (BufferedReader reader = new BufferedReader(
                    new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8))) {
                String line;
                while ((line = reader.readLine()) != null) {
                    content.append(line);
                }
            }

            return ResponseEntity.ok()
                    .contentType(MediaType.TEXT_PLAIN)
                    .body(content.toString());
        } catch (IOException e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body("文件读取失败: " + e.getMessage());
        }
    }


    @GetMapping("/getWenZhang")
    public void getWenZhang(HttpServletRequest request,
                            HttpServletResponse response,
                            @RequestParam(value = "id", required = false) String id,
                            @RequestParam(value = "domainUrl", required = false) String domainUrl) throws IOException {

        System.out.println("=====getWenZhang======"+id+id);
        System.out.println("=====文件访问接口======"+id+domainUrl);

        String randomCode = generateRandomCode(6);

        Long outsiderealmId=null;
        Long ids =0L;
        String deCrypt =  Base64Util.decryptNumber(id);
        if (StringUtils.isNotEmpty(deCrypt)){
            ids = Long.parseLong(deCrypt);
        }
        ArticletaskDTO articletaskDTO = catArticletaskTableService.selectCatArticletaskById(ids);

        if (articletaskDTO != null){
            if (articletaskDTO.getOutsiderealmId() != null){
                outsiderealmId = articletaskDTO.getOutsiderealmId();
            }
        }else{
            return;
        }
        String redirectUrl ="";
        CatOutsiderealmTable catOutsiderealmTable = iCatOutsiderealmTableService.selectCatOutsiderealmByDomain(domainUrl);
        if (articletaskDTO != null){
            if (StringUtils.isNotEmpty(articletaskDTO.getDomainName())){
                 redirectUrl = articletaskDTO.getDomainName()+"/"+"wenzhang/" +generateRandomCode(4)+"/"+"article_"+id+"/"+randomCode;
            }
        }
        System.out.println("=====redirectUrl======"+id+redirectUrl);
       System.out.println("=====文件访问接口======"+id+domainUrl);
       // String redirectUrl = "https://web.jiubeimao.com/article/editArticleTask";
        if (id != null || domainUrl != null) {
            redirectUrl += "?";
            if (id != null) {
                redirectUrl += "id=" + id;
            }
           /* if (domainUrl != null) {
                redirectUrl += (id != null ? "&" : "") + "domainUrl=" + domainUrl;
            }*/
           // redirectUrl += (id != null ? "&" : "") + "code=" + randomCode;
        }
        response.sendRedirect(redirectUrl);
    }


    // 生成随机字符串的方法
    private String generateRandomCode(int length) {
        String characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
        StringBuilder randomCode = new StringBuilder();
        Random random = new Random();

        for (int i = 0; i < length; i++) {
            int index = random.nextInt(characters.length());
            randomCode.append(characters.charAt(index));
        }

        return randomCode.toString();
    }


    @GetMapping("/getDataRequest")
    public void getDataRequest(HttpServletRequest request,
                            HttpServletResponse response,
                            @RequestParam(value = "id", required = false) String id,
                            @RequestParam(value = "domainUrl", required = false) String domainUrl) throws IOException {

        System.out.println("=====getWenZhang======"+id+id);
        System.out.println("=====文件访问接口======"+id+domainUrl);
        Long outsiderealmId=null;
        Long ids =0L;
        String deCrypt =  Base64Util.decryptNumber(id);
        if (StringUtils.isNotEmpty(deCrypt)){
            ids = Long.parseLong(deCrypt);
        }
        ArticletaskDTO articletaskDTO = catArticletaskTableService.selectCatArticletaskById(ids);

        if (articletaskDTO != null){
            if (articletaskDTO.getOutsiderealmId() != null){
                outsiderealmId = articletaskDTO.getOutsiderealmId();
            }
        }else{
            return;
        }
        String redirectUrl ="";
        CatOutsiderealmTable catOutsiderealmTable = iCatOutsiderealmTableService.selectCatOutsiderealmByDomain(domainUrl);
        if (articletaskDTO != null){
            if (StringUtils.isNotEmpty(articletaskDTO.getDomainName())){
                redirectUrl = articletaskDTO.getDomainName()+"/"+"wenzhang/"+"article_"+id+".html";
            }
        }
        System.out.println("=====redirectUrl======"+id+redirectUrl);
        System.out.println("=====文件访问接口======"+id+domainUrl);
        // String redirectUrl = "https://web.jiubeimao.com/article/editArticleTask";
        if (id != null || domainUrl != null) {
            redirectUrl += "?";
            if (id != null) {
                redirectUrl += "id=" + id;
            }
            if (domainUrl != null) {
                redirectUrl += (id != null ? "&" : "") + "domainUrl=" + domainUrl;
            }
        }
        response.sendRedirect(redirectUrl);
    }

   //http://testa.ngvc.cn/getViewArticle/?id=bms=&domainUrl=http://testa.ngvc.cn
    @GetMapping("/getViewArticle")
    public void getViewArticle(HttpServletRequest request,
                            HttpServletResponse response,
                            @RequestParam(value = "id", required = false) String id,
                            @RequestParam(value = "domainUrl", required = false) String domainUrl) throws IOException {

        System.out.println("=====getViewArticle======"+id);
        // 验证当前域名
        String serverName = request.getServerName();
        String deCrypt = Base64Util.decryptNumber(id);
        Long ids = Long.parseLong(deCrypt);
        System.out.println("serverName-----------"+serverName);
        ArticletaskDTO articletaskDTO = catArticletaskTableService.selectCatArticletaskById(ids);
        System.out.println("getDomainName-----------"+articletaskDTO.getDomainName());
        if (articletaskDTO == null) {
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }

        try {
            URL domainUrlHost = new URL(articletaskDTO.getDomainName());
            String domainHost = domainUrlHost.getHost();

            // 先检查服务器域名是否匹配
            boolean isServerDomainMatch = serverName.equalsIgnoreCase(domainHost);

            // 如果服务器域名不匹配，再检查二维码域名
            boolean isQrDomainMatch = false;
            if (!isServerDomainMatch && domainUrl != null && !domainUrl.isEmpty()) {
                CatOutsiderealmTable catOutsiderealmTable = iCatOutsiderealmTableService.selectCatOutsiderealmByDomain(domainUrl);
                isQrDomainMatch = (catOutsiderealmTable != null && catOutsiderealmTable.getOutSideRealmId() != null);
            }

            // 只要其中一个域名匹配就允许通过
            if (!isServerDomainMatch && !isQrDomainMatch) {
                response.sendError(HttpServletResponse.SC_NOT_FOUND);
                return;
            }
        } catch (MalformedURLException e) {
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }
        // 读取静态文件
        String filePath = "/home/cat/wenzhang/article_" + id + ".html";
        System.out.println("filePath-----------"+filePath);
        File file = new File(filePath);
        if (!file.exists()) {
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }
        // 设置响应头
        response.setContentType("text/html;charset=UTF-8");
        System.out.println("queryParams2-----------");
        try (BufferedReader reader = new BufferedReader(new FileReader(file));
             PrintWriter out = response.getWriter()) {

            StringBuilder content = new StringBuilder();
            String line;

            // 读取文件内容
            while ((line = reader.readLine()) != null) {
                content.append(line).append("\n");
            }

            // 构建URL参数
            String queryParams = String.format("?id=%s",
                    URLEncoder.encode(id)
            );
            if (domainUrl != null && !domainUrl.isEmpty()) {
                queryParams += "&domainUrl=" + URLEncoder.encode(domainUrl);
            }


            System.out.println("queryParams-----------"+queryParams);
            // 在 HTML 内容中找到第一个 <a> 标签或 <form> 标签，添加 URL 参数
            String processedContent = content.toString().replaceFirst(
                    "(<a\\s+href=\"[^\"]*\"|<form\\s+action=\"[^\"]*\")",
                    "$1" + queryParams
            );
            // 输出处理后的内容
            out.write(processedContent);
            out.flush();
        }
    }




}
